//
//  JSQMapViewController.m
//  Conversation
//
//  Created by C_HAO on 15/10/13.
//  Copyright © 2015年 CHAOO. All rights reserved.
//

#import "JSQMapViewController.h"


@interface JSQMapViewController () <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, copy) NSArray *placemarks;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *mapViewHeightConstraint;
@property (weak, nonatomic) IBOutlet UIView *activityShowView;

@end

@implementation JSQMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"位置信息";

    [self promptOpenLocation];

    _mapView.showsUserLocation = YES;

    _locationManager.delegate = self;

    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.distanceFilter = 100;

    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        [_locationManager requestWhenInUseAuthorization];
    }


    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];

    if (_mapViewType == JSQMapViewTypeChoice) {
        _annotaion = [[JSQMapLocation alloc] init];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"正在定位" style:UIBarButtonItemStylePlain target:self action:@selector(sendLocation)];
        self.navigationItem.rightBarButtonItem.enabled = NO;
    } else {
        [_activityShowView removeFromSuperview];
        [self.view removeConstraint:_mapViewHeightConstraint];
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_mapView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];
        [self.view updateConstraints];
        [_mapView setRegion:MKCoordinateRegionMakeWithDistance(_annotaion.coordinate, 2000, 2000)];
        [_mapView addAnnotation:_annotaion];
        [_mapView selectAnnotation:_annotaion animated:YES];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_locationManager startUpdatingLocation];
}

- (void)sendLocation {
    if ([_delegate respondsToSelector:@selector(didSendMapLocation:location:)]) {
        [_delegate didSendMapLocation:_annotaion.addressTitle location:_annotaion.location];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    MKCoordinateRegion regin = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 2000, 2000);

    if (_mapViewType == JSQMapViewTypeChoice) {
        [_mapView setRegion:regin];
    }


    [_locationManager stopUpdatingLocation];

    CLGeocoder *geocoder = [[CLGeocoder alloc] init];

    __weak typeof(self) VC = self;
    [geocoder reverseGeocodeLocation:userLocation.location completionHandler:
     ^(NSArray *placemarks, NSError *error) {

        if (!error) {
            CLPlacemark *placemark = [placemarks firstObject];

            VC.mapView.userLocation.subtitle = placemark.name;
            VC.mapView.userLocation.title = @"您的位置";

            if (VC.mapViewType == JSQMapViewTypeChoice) {
                VC.annotaion.coordinate = VC.mapView.userLocation.coordinate;
                VC.annotaion.addressTitle = [VC addressTitle:placemark];
                VC.annotaion.location = userLocation.location;
                VC.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(sendLocation)];
                VC.navigationItem.rightBarButtonItem.enabled = YES;
                [VC.mapView selectAnnotation:VC.mapView.userLocation animated:YES];
            }


            if (_mapViewType == JSQMapViewTypeChoice) {
                VC.placemarks = placemarks;
                [_activityShowView removeFromSuperview];
                [VC.tableView reloadData];
            }

        }
    }];
}

- (NSString *)addressTitle:(CLPlacemark *)placemark {
    NSString *thoroughfare = placemark.thoroughfare;
    if (!thoroughfare) {
        thoroughfare = @"";
    }
    NSString *locality = placemark.locality;
    if (!locality) {
        locality = @"";
    }
    NSString *subLocality = placemark.subLocality;
    if (!subLocality) {
        subLocality = @"";
    }

    return [NSString stringWithFormat:@"%@%@%@", locality, subLocality, thoroughfare];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    [_locationManager startUpdatingLocation];
}

- (BOOL)promptOpenLocation {
    _locationManager = [[CLLocationManager alloc] init];

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        [_locationManager requestAlwaysAuthorization];
    }

    [_locationManager startUpdatingLocation];

    if (![CLLocationManager locationServicesEnabled]) {

        NSString *message = @"您的手机目前并未开启定位服务，如欲开启定位服务，请至设定->隐私->定位服务，开启本程序的定位服务功能";
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"无法定位" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];

        return NO;

    } else {

        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
            return YES;
        }
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
                return YES;
            }
            if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {
                return YES;
            }
        }


        if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorized && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined) {

            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];

            CFShow((__bridge CFTypeRef)(infoDictionary));

            NSString *message = @"您的手机目前并未开启定位服务，如欲开启定位服务，请至设定->隐私->定位服务，开启本程序的定位服务功能";
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"无法定位" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alertView show];

            return NO;
        } else {
            return YES;
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _placemarks.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];

    CLPlacemark *placemark = [_placemarks objectAtIndex:indexPath.row];
    cell.textLabel.text = placemark.name;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont systemFontOfSize:15];

    if (_annotaion.indexPath.row == indexPath.row) {
        cell.textLabel.textColor = self.view.tintColor;
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.textLabel.textColor = [UIColor blackColor];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    [_mapView removeAnnotation:_annotaion];

    CLPlacemark *placemark = [_placemarks objectAtIndex:indexPath.row];
    MKCoordinateRegion regin = MKCoordinateRegionMakeWithDistance(placemark.location.coordinate, 2000, 2000);

    [_mapView setRegion:regin animated:YES];

    if (indexPath.row == 0) {
        _annotaion.indexPath = indexPath;
        [_mapView selectAnnotation:_mapView.userLocation animated:YES];

    } else {

        _annotaion.indexPath = indexPath;
        _annotaion.addressTitle = placemark.name;
        _annotaion.coordinate = placemark.location.coordinate;
        _annotaion.location = placemark.location;

        [_mapView addAnnotation:_annotaion];

        [_mapView selectAnnotation:_annotaion animated:YES];
    }

    [tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
